package com.plat.project.content.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.plat.api.common.OrderType;
import com.plat.api.config.WxConfig;
import com.plat.api.config.WxPayCommentConfig;
import com.plat.api.dao.api.PlatWechatLiveRoomDao;
import com.plat.api.util.YmalPropertiesUtil;
import com.plat.common.utils.poi.ExcelUtil;
import com.plat.project.content.domain.*;
import com.plat.project.content.service.*;
import com.plat.project.content.service.impl.PlatGoodsServiceImpl;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.plat.framework.aspectj.lang.annotation.Log;
import com.plat.framework.aspectj.lang.enums.BusinessType;

import com.plat.framework.web.controller.BaseController;
import com.plat.framework.web.domain.AjaxResult;
import com.plat.framework.web.page.TableDataInfo;

/**
 * 顶大Controller
 *
 * @author plat
 * @date 2020-08-01
 */
@RestController
@RequestMapping("/content/order")
public class PlatOrderController extends BaseController {
    @Autowired
    private IPlatOrderService platOrderService;
    @Autowired
    private IPlatOrderDetailService platOrderDetailService;
    @Autowired
    private IPlatVideoService iPlatVideoService;
    @Autowired
    private IPlatWechatLiveRoomService iPlatWechatLiveRoomService;
    @Autowired
    private IPlatGoodsService iPlatGoodsService;
    @Autowired
    private IPlatUserService iPlatUserService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private IPlatOrderRefundService iPlatOrderRefundService;

    /**
     * 查询顶大列表
     */
    @PreAuthorize("@ss.hasPermi('content:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(PlatOrder platOrder) {
        startPage();
        List<PlatOrder> list = platOrderService.selectPlatOrderList(platOrder);
        return getDataTable(list);
    }

    /**
     * 导出顶大列表
     */
    @PreAuthorize("@ss.hasPermi('content:order:export')")
    @Log(title = "顶大", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PlatOrder platOrder) {
        List<PlatOrder> list = platOrderService.selectPlatOrderList(platOrder);
        ExcelUtil<PlatOrder> util = new ExcelUtil<PlatOrder>(PlatOrder.class);
        return util.exportExcel(list, "order");
    }

    /**
     * 获取顶大详细信息
     */
    @PreAuthorize("@ss.hasPermi('content:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(platOrderService.selectPlatOrderById(id));
    }

    /**
     * 新增顶大
     */
    @PreAuthorize("@ss.hasPermi('content:order:add')")
    @Log(title = "顶大", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PlatOrder platOrder) {
        return toAjax(platOrderService.insertPlatOrder(platOrder));
    }

    /**
     * 修改顶大
     */
    @PreAuthorize("@ss.hasPermi('content:order:edit')")
    @Log(title = "顶大", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PlatOrder platOrder) {
        return toAjax(platOrderService.updatePlatOrder(platOrder));
    }

    /**
     * 删除顶大
     */
    @PreAuthorize("@ss.hasPermi('content:order:remove')")
    @Log(title = "顶大", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(platOrderService.deletePlatOrderByIds(ids));
    }

    /**
     * 查看订单详情
     */
    @PreAuthorize("@ss.hasPermi('content:order:getOrderDetailList')")
    @Log(title = "查看订单详情", businessType = BusinessType.OTHER)
    @PostMapping("/getOrderDetailList")
    public AjaxResult getOrderDetailList(@RequestBody PlatOrder platOrder) {
        platOrder = platOrderService.selectByOrderNo(platOrder.getOrderNo());
        List<OrderDetail> list = platOrderDetailService.getOrderDetail(platOrder.getOrderNo(), platOrder.getOrderType());
        for (OrderDetail orderDetail : list) {
            if (orderDetail.getPayStatus().equals(OrderType.FINISH_PAY)) {
                orderDetail.setPayStatusTxt("支付成功");
            }
            if (platOrder.getPayStatus().equals(OrderType.NO_PAY)) {
                orderDetail.setPayStatusTxt("订单未支付");
            }
            if (platOrder.getExpressStatus().equals(OrderType.ORDER_EXPRESS_NO_DISTRIBUTE)) {
                orderDetail.setExpressStatusTxt("新进订单需要打包");
            }
            if (platOrder.getExpressStatus().equals(OrderType.ORDER_EXPRESS_DISTRIBUTE)) {
                orderDetail.setExpressStatusTxt("订单发货");
            }
            if (platOrder.getExpressStatus().equals(OrderType.ORDER_EXPRESS_WAITING)) {
                orderDetail.setExpressStatusTxt("订单运输途中");
            }
            if (platOrder.getExpressStatus().equals(OrderType.ORDER_EXPRESS_FINISH)) {
                orderDetail.setExpressStatusTxt("订单收货");
            }
        }
        List<Map<String, Object>> list1 = new ArrayList<>();
        for (OrderDetail detail : list) {
            Map<String, Object> result = new HashMap<>();
            result.put("goodsType", getType(detail.getOrderType()));
            if (getType(detail.getOrderType()).equals(OrderType.LIVE)) {
                PlatWechatLiveRoom room = iPlatWechatLiveRoomService.selectPlatWechatLiveRoomById(detail.getGoodsId());
                result.put("detail", room.getDetail());
                result.put("goodsName", room.getDetail());
                result.put("GoodsType", "直播");
            }
            if (getType(detail.getOrderType()).equals(OrderType.VIDE0)) {
                PlatVideo platVideo = iPlatVideoService.selectPlatVideoById(detail.getGoodsId());
                result.put("detail", platVideo.getDetail());
                result.put("goodsName", platVideo.getVideoName());
                result.put("GoodsType", "视频");
            }
            if (getType(detail.getOrderType()).equals(OrderType.YSP)) {
                PlatGoods platGoods = iPlatGoodsService.selectPlatGoodsById(detail.getGoodsId());
                result.put("detail", platGoods.getGoodsDeatail());
                result.put("goodsName", platGoods.getGoodsName());
                result.put("GoodsType", "艺术品");
            }
            result.put("price", detail.getOrderPrice());
            list1.add(result);
        }
        //根据订单类型查询商品信息   目前：三种类型 拍卖、视频、直播
        Map<String, Object> map = new HashMap<>();
        map.put("orderNo", platOrder.getOrderNo());
        map.put("createTime", DateUtil.format(platOrder.getCreateTime(), "yyyy年MM月dd日 hh时mm分ss秒"));
        PlatUser platUser = iPlatUserService.selectPlatUserById(platOrder.getUserId());
        map.put("userName", platUser.getName());
        map.put("phone", platUser.getPhone());
        map.put("amt", platOrder.getOrderRealPrice());
        map.put("payStatus", platOrder.getPayStatus() == 1 ? "已支付" : "未支付");
        map.put("goodsList", list1);
        return AjaxResult.success(map);
    }

    private String getType(String orderType) {
        String type = "";
        if (orderType.equals(OrderType.AUCTION)) {
            type = "拍卖";
        }
        if (orderType.equals(OrderType.LIVE)) {
            type = "直播";
        }
        if (orderType.equals(OrderType.VIDE0)) {
            type = "视频";
        }
        if (orderType.equals(OrderType.YSP)) {
            type = "艺术品";
        }
        return type;
    }

    /**
     * 退款
     */
    @PreAuthorize("@ss.hasPermi('content:order:refund')")
    @Log(title = "退款", businessType = BusinessType.OTHER)
    @PostMapping("/refund")
    public AjaxResult refund(@RequestBody PlatOrder platOrder) throws Exception {
        PlatOrderRefund platOrderRefund = iPlatOrderRefundService.selectByOrderNo(platOrder.getOrderNo());
        PlatOrder order = platOrderService.selectByOrderNo(platOrder.getOrderNo());
        if (platOrderRefund.getRefundStatus().equals(OrderType.ORDER_REFUND_REJECT)) {
            return AjaxResult.error("该笔已拒绝退款,不能再次退款");
        }
        WxPayRefundRequest refundRequest = new WxPayRefundRequest();
        refundRequest.setOutTradeNo(platOrderRefund.getOrderNo());
        refundRequest.setOutRefundNo(RandomUtil.randomNumbers(18));
        String payAmt = platOrderRefund.getRefundAmt().toString();
        Double d = Double.valueOf(payAmt) * 100;
        refundRequest.setTotalFee(d.intValue());
        refundRequest.setRefundFee(d.intValue());
        refundRequest.setNotifyUrl(YmalPropertiesUtil.getValue("wxpay.refund-notify-url").toString());
        refundRequest.setNonceStr(refundRequest.getNonceStr());
        refundRequest.setSign(refundRequest.getSign());
        refundRequest.setSignType(refundRequest.getSignType());
        wxPayService.setConfig(WxPayCommentConfig.getRefundConfig());
        String msg;
        boolean flag = false;
        try {
            WxPayRefundResult wxPayRefundResult = wxPayService.refund(refundRequest);
            msg = wxPayRefundResult.getReturnMsg();
        } catch (WxPayException e) {
            e.printStackTrace();
            msg = e.getErrCodeDes();
            flag = true;
        }
        if (flag) {
            return AjaxResult.error(msg);
        } else {
            platOrderRefund.setRefundStatus(OrderType.ORDER_REFUND_FINISH);
            order.setRefundStatus(OrderType.ORDER_REFUND_FINISH);
        }
        platOrderService.updatePlatOrder(order);
        iPlatOrderRefundService.updatePlatOrderRefund(platOrderRefund);
        return AjaxResult.success(msg);
    }

    /**
     * 退款
     */
    @PreAuthorize("@ss.hasPermi('content:order:refund')")
    @Log(title = "拒绝退款", businessType = BusinessType.OTHER)
    @PostMapping("/reject")
    public AjaxResult reject(@RequestBody PlatOrder platOrder) {
        PlatOrderRefund platOrderRefund = iPlatOrderRefundService.selectByOrderNo(platOrder.getOrderNo());
        if (platOrderRefund.getRefundStatus().equals(OrderType.ORDER_REFUND_REJECT)) {
            return AjaxResult.error("该笔已拒绝退款");
        }
        PlatOrder order = platOrderService.selectByOrderNo(platOrder.getOrderNo());
        platOrderRefund.setRefundStatus(OrderType.ORDER_REFUND_REJECT);
        order.setRefundStatus(OrderType.ORDER_REFUND_REJECT);
        iPlatOrderRefundService.updatePlatOrderRefund(platOrderRefund);
        platOrderService.updatePlatOrder(order);
        return AjaxResult.success("拒绝退款");
    }
}
